package com.fdb.efp.batch.service.impl;

import com.fdb.basic.framework.core.util.DateUtility;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.efp.batch.common.constant.BdLoanConstant;
import com.fdb.efp.batch.service.facade.AccLoanBatchService;
import com.fdb.efp.batch.service.facade.NewAccLoanBatchService;
import com.fdb.efp.batch.service.util.SDicMappingUtil;
import com.fdb.efp.console.service.facade.PrdInfoService;
import com.fdb.efp.console.service.vo.PrdInfoVO;
import com.fdb.efp.ctr.service.facade.CtrLoanContService;
import com.fdb.efp.ctr.service.vo.CtrLoanContVO;
import com.fdb.efp.limit.common.LimitConstant;
import com.fdb.efp.loan.service.facade.*;
import com.fdb.efp.loan.service.vo.AccLoanVO;
import com.fdb.efp.loan.service.vo.GzBankLoanFileTempVO;
import com.fdb.efp.loan.service.vo.LoanAccountTempVO;
import com.fdb.efp.nls.service.facade.NlsApplyInfoService;
import com.fdb.efp.nls.service.vo.NlsApplyInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service("newAccLoanBatchService")
public class NewAccLoanBatchServiceImpl implements NewAccLoanBatchService {
    private static Logger logger = LoggerFactory.getLogger(NewAccLoanBatchServiceImpl.class);
    public final static String DN_STS_1 = "1";// 发放状态：1联合放款成功
    public final static String DN_STS_3 = "3";// 发放状态：3待放款

    @Autowired
    @Qualifier("nlsApplyInfoService")
    private NlsApplyInfoService nlsApplyInfoService;// 放款申请信息

    @Autowired
    @Qualifier("accLoanService")
    private AccLoanService accLoanService;// 借据信息

    @Autowired
    @Qualifier("accoutErroTempService")
    private AccoutErroTempService accoutErroTempService;

    @Autowired
    @Qualifier("gzBankLoanFileTempService")
    private GzBankLoanFileTempService gzBankLoanFileTempService;

    @Autowired
    @Qualifier("loanAccountTempService")
    private LoanAccountTempService loanAccountTempService;

    @Autowired
    @Qualifier("prdInfoService")
    private PrdInfoService prdInfoService;

    @Autowired
    @Qualifier("accLoanRepayPlanService")
    private LoanRepayPlanService loanRepayPlanService;

    @Autowired
    @Qualifier("loanRepayDetailService")
    private LoanRepayDetailService loanRepayDetailService;


    @Autowired
    @Qualifier("ctrLoanContService")
    private CtrLoanContService ctrLoanContService;

    /**
     *
     * 根據马上同步过来的临时表数据修改台账表 <br>
     * 0.2:ludayong:2019年3月6日 下午5:10:56:修复贷款借据临时信息为空时，出现空指针异常<br>
     * 0.2:ludayong:2019年3月6日 下午5:10:56:增加逾期应收赋值<br>
     * @author cenyj
     * @since 2018年12月25日 下午3:35:23
     * @date 2019年3月6日 下午5:10:56
     * @version 0.2
     */
    @Override
    public boolean batchUpdateAccLoanFromMaTxt() throws Exception {
        boolean result = false;
        logger.info("日终批量修改从马上同步过来的临时表数据到台账表：");
        int num = 0;
        try {
            // 分页大小
            Integer pageSize = 1000;
            // 分页信息
            GzBankLoanFileTempVO pageInfo = new GzBankLoanFileTempVO();
            // 页数
            int page = 1;
            // pageSize初始化
            if (pageSize > 0) {
                pageInfo.setSize(pageSize);
            } else {
                pageInfo.setSize(1000);
            }
            // 判断循环次数
            int size = gzBankLoanFileTempService.queryCount();
            String size_msg = "【借据信息表临时表】数据量：" + size;
            logger.info(size_msg, "message{}");
            int loopCount = (size / pageInfo.getSize()) + 1;

            // 对账数据
            BigDecimal loanAmountTotal = BigDecimal.ZERO;
            BigDecimal principalBalTotal = BigDecimal.ZERO;
            BigDecimal overduePrinTotal = BigDecimal.ZERO;
            BigDecimal interestBalTotal = BigDecimal.ZERO;
            BigDecimal overdueIntTotal = BigDecimal.ZERO;
            BigDecimal penaltyBalTotal = BigDecimal.ZERO;
            for (int i = 0; i < loopCount; i++) {
                String page_msg = "【借据信息表临时表】当前页数：" + pageInfo.getPage() + "，分页大小：" + pageInfo.getSize();
                logger.info(page_msg, "message{}");
                // 分页查询【借据信息表临时表】数据
                List<GzBankLoanFileTempVO> tempList = gzBankLoanFileTempService.queryByPage(pageInfo);
                if (Objects.nonNull(tempList) && !tempList.isEmpty()) {
                    // 同步借据信息
                    syncLoanInfo(tempList);
                    // 对账数据
                    loanAmountTotal = loanAmountTotal.add(tempList.stream().map(GzBankLoanFileTempVO::getTxnAmt).reduce(BigDecimal.ZERO, BigDecimal::add));
                    principalBalTotal = principalBalTotal.add(tempList.stream().map(GzBankLoanFileTempVO::getPrincipalBal).reduce(BigDecimal.ZERO, BigDecimal::add));
                    overduePrinTotal = overduePrinTotal.add(tempList.stream().map(GzBankLoanFileTempVO::getOverduePrin).reduce(BigDecimal.ZERO, BigDecimal::add));
                    interestBalTotal = interestBalTotal.add(tempList.stream().map(GzBankLoanFileTempVO::getInterestBal).reduce(BigDecimal.ZERO, BigDecimal::add));
                    overdueIntTotal = overdueIntTotal.add(tempList.stream().map(GzBankLoanFileTempVO::getOverdueInt).reduce(BigDecimal.ZERO, BigDecimal::add));
                    penaltyBalTotal = penaltyBalTotal.add(tempList.stream().map(GzBankLoanFileTempVO::getPenaltyBal).reduce(BigDecimal.ZERO, BigDecimal::add));
                }
                pageInfo.setPage(++page);
            }
            // 先校对台账对账临时表的记录条数跟同步过来的数据是否一致 如果一致 再批量修改loanTempList
//		List<GzBankLoanFileTempVO> list = gzBankLoanFileTempService.queryGzBankLoanFileTemp();
            //同步信息为空，返回false
//		if(Objects.isNull(list)) {
//			logger.info("日终批量-同步马上的贷款借据信息为空！");
//			return result;
//		}

            List<LoanAccountTempVO> accountList = loanAccountTempService.getLoanAccountTempList();
            LoanAccountTempVO loanAccountTempModel = null;//new LoanAccountTempVO();
            logger.info("List<GzBankLoanFileTempVO> list = gzBankLoanFileTempService.queryGzBankLoanFileTemp()马上同步过来的临时数据记录条数：" + size);
            logger.info("开始对账");
            /// 对账表字段
//		BigDecimal loanAmountTotal = list.stream().map(GzBankLoanFileTempVO::getTxnAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
//		BigDecimal principalBalTotal = list.stream().map(GzBankLoanFileTempVO::getPrincipalBal).reduce(BigDecimal.ZERO, BigDecimal::add);
//		BigDecimal overduePrinTotal = list.stream().map(GzBankLoanFileTempVO::getOverduePrin).reduce(BigDecimal.ZERO, BigDecimal::add);
//		BigDecimal interestBalTotal = list.stream().map(GzBankLoanFileTempVO::getInterestBal).reduce(BigDecimal.ZERO, BigDecimal::add);
//		BigDecimal overdueIntTotal = list.stream().map(GzBankLoanFileTempVO::getOverdueInt).reduce(BigDecimal.ZERO, BigDecimal::add);
//		BigDecimal penaltyBalTotal = list.stream().map(GzBankLoanFileTempVO::getPenaltyBal).reduce(BigDecimal.ZERO, BigDecimal::add);
            //BigDecimal principalTotal = listFileTempAll.stream().map(GzBankRepayPlanFileTempVO::getPrincipal).reduce(BigDecimal.ZERO, BigDecimal::add);


            BigDecimal loanAmountTotalSum =  loanAmountTotal == null ? BigDecimal.ZERO : loanAmountTotal;
            BigDecimal principalBalTotalSum =  principalBalTotal == null ? BigDecimal.ZERO : principalBalTotal;
            BigDecimal overduePrinTotalSum =  overduePrinTotal == null ? BigDecimal.ZERO : overduePrinTotal;
            BigDecimal interestBalTotalSum =  interestBalTotal == null ? BigDecimal.ZERO : interestBalTotal;
            BigDecimal overdueIntTotalSum =  overdueIntTotal == null ? BigDecimal.ZERO : overdueIntTotal;
            BigDecimal penaltyBalTotalSum =  penaltyBalTotal == null ? BigDecimal.ZERO : penaltyBalTotal;

            int accountCountTemp = 0;// 台账对账表记录的条数
            int loanTempDatasize = 0;// 实际同步过来的数据总条数
            if (accountList != null && accountList.size() > 0) {
                loanAccountTempModel = accountList.get(0);
            }
            if (loanAccountTempModel != null) {
                accountCountTemp = loanAccountTempModel.getDataCount() == null ? 0 : loanAccountTempModel.getDataCount();
                String tableName = "GzBankLoanFileTemp";
                if (loanAccountTempModel.getLoanAmountTotal().compareTo(loanAmountTotalSum) != 0) {
                    String erroMsg = "放款总额getLoanAmountTotal不对";
                    String acountTotal = "" + loanAccountTempModel.getLoanAmountTotal();
                    String tempTotal = "" + loanAmountTotalSum;
                    accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
                }

                if (loanAccountTempModel.getPrincipalBalTotal().compareTo(principalBalTotalSum) != 0) {
                    String erroMsg = "未还本金总额getPrincipalBalTotal不对";
                    String acountTotal = "" + loanAccountTempModel.getPrincipalBalTotal();
                    String tempTotal = "" + principalBalTotalSum;
                    accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
                }
                if (loanAccountTempModel.getOverduePrinTotal().compareTo(overduePrinTotalSum) != 0) {
                    String erroMsg = "逾期本金总额getOverduePrinTotal不对";
                    String acountTotal = "" + loanAccountTempModel.getOverduePrinTotal();
                    String tempTotal = "" + overduePrinTotalSum;
                    accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
                } //
                if (loanAccountTempModel.getInterestBalTotal().compareTo(interestBalTotalSum) != 0) {
                    String erroMsg = "未还利息总额getInterestBalTotal不对";
                    String acountTotal = "" + loanAccountTempModel.getInterestBalTotal();
                    String tempTotal = "" + interestBalTotalSum;
                    accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
                }
                if (loanAccountTempModel.getOverdueIntTotal().compareTo(overdueIntTotalSum) != 0) {
                    String erroMsg = "逾期利息总额getOverdueIntTotal不对";
                    String acountTotal = "" + loanAccountTempModel.getOverdueIntTotal();
                    String tempTotal = "" + overdueIntTotalSum;
                    accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
                }
                if (loanAccountTempModel.getPenaltyBalTotal().compareTo(penaltyBalTotalSum) != 0) {
                    String erroMsg = "罚息总额getPenaltyBalTotal不对";
                    String acountTotal = "" + loanAccountTempModel.getPenaltyBalTotal();
                    String tempTotal = "" + penaltyBalTotalSum;
                    accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
                }
            }

            //loanTempDatasize = list.size();
            loanTempDatasize = size;

            logger.info("台账对账表记录的条数loanTempDatasize：" + loanTempDatasize + "实际同步过来的数据总条数loanTempDatasize" + loanTempDatasize);
            if (loanTempDatasize != accountCountTemp) {
                // 如果条数不一样，则记录到 erro_msg表
                String erroMsg = "记录条数不对";
                String tableName = "GzBankLoanFileTemp";
                String tempTotal = "" + loanTempDatasize;
                String acountTotal = "" + accountCountTemp;
                accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");

            }
            logger.info("结束对账");
            // 同步过来的数据条数一致，则批量修改
            // 1先查出gz_bank_loan__file_temp临时表的所有数据，再根据借据号 和 （放款=成功状态：放款流水表里） 才去对应本地表进行修改
            ////// 2对于我们二次审批通过，但没有收到马上的放款通知结果，（只是接收这个状态没成功，但所有的流程都走完了，因此我们没有更新放款状态和借据信息。。。）
            // 放款状态：放款中
            ////// insert 据借据号 和 （放款=放款中的状态：放款流水表里） 如果插入成功了 把 放款中的状态 改为 成功的状态 状态值问达永
            result = true;
            logger.info("整个借据数据方法结束，rs："+result );
        } catch (Exception e) {
            logger.info("同步马上借据信息发生异常");
            logger.error("同步马上借据信息出错!", e);
            e.printStackTrace();
            String tableName = "AccLoan借据表";
            String erroMsg = "";
            String tempTotal = "";
            String acountTotal = "";
            String type = "0";
            String updateDelInster = "更新";
            String no = "";
            String eMsg = e.getMessage();
            accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);
        }
        return result;
    }

    // 封装台帐信息 新增
    public AccLoanVO insetAccLoan(GzBankLoanFileTempVO loantemp) throws Exception {
        // 封装台帐信息
        AccLoanVO accLoan = new AccLoanVO();
        // 2019-1-23 modify by cyj
        /*
         * 贷款本金余额（原来对应 正常贷款余额(元)normal_balance不赋值） 修改为loan_balance借据余额
         * 贷款利息余额（int_accr应收利息（已记未结 修改为：应收利息累计rece_int_cumu） 逾期贷款本金余额（逾期贷款余额43
         * overdue_balance）修改为unpd_prin_bal 拖欠本金 逾期利息 由原来的逾期应收overdue_rece_int修改为欠息累计
         * delay_int_cumu 罚息余额unpd_int_arr_prn1 修改为 应收罚息unpd_int_arr_prn
         */
        accLoan.setBillNo(loantemp.getRefNbr());
        accLoan.setContNo(loantemp.getRefNbr());
        accLoan.setPrdCode(loantemp.getProductCd());// 根据产品编号查相关数据
        accLoan.setCurType(loantemp.getCurrency());// 取字典库数据CNY 人民币//156?
        String statusMy = "";
        switch (loantemp.getTxnStatus()) {
            case "1":// 1：正常
                statusMy = "1";
                break;
            case "2":// 2：延期
            case "3":// 3：提前结清
            case "5":// 5：结清

                statusMy = "4";// 结清
                break;
            case "9":// 9理赔结清
                statusMy = "11";// 理赔结清
                break;
            case "4":// 4：逾期
            case "7":// 7：逾期90天强制终止
                statusMy = "10";// 逾期
                break;
            case "6":
                statusMy = "9";// 核销
                break;
            default:
                break;
        }
        //  modify by ludayong 2020/01/16 【马上】新增贷款状态转换为网贷台账状态
        // 贷款状态转换为网贷台账状态
        statusMy = SDicMappingUtil.getLocalSysDicVal("TxnStatus", loantemp.getTxnStatus());
        logger.info("贷款状态：" + loantemp.getTxnStatus() + "，转换为网贷台账状态：" + statusMy);

        accLoan.setAccountStatus(statusMy);// 取字典库数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//
        accLoan.setLoanStartDate(DateUtility.format8To10(loantemp.getTxnDate()));
        // curr_term 加上 当前期数（在本地表缺少需加上）
        accLoan.setCurrTerm(new BigDecimal(loantemp.getCurrTerm() == null ? 0 : loantemp.getCurrTerm()));
        // 报表需要字段 ：overdue_days 逾期天数 loan_term贷款期限（init_term） load_term_type期限类型 （默认:月）
        // curr_term当前期数
        accLoan.setOverdueDays(
                new BigDecimal(loantemp.getOverdueDays() == null ? 0 : loantemp.getOverdueDays()));
        accLoan.setLoanTerm(new BigDecimal(loantemp.getInitTerm() == null ? 0 : loantemp.getInitTerm()));
        accLoan.setLoadTermType(BdLoanConstant.TERM_TYPE_M);
        accLoan.setIntRateType(loantemp.getIntRateType());//利率类型
        accLoan.setLoanAmount( loantemp.getTxnAmt() == null ? BigDecimal.ZERO : loantemp.getTxnAmt());
        //如果没有逾期，则为空
        if(loantemp.getOverdueDate() !=null) {
            accLoan.setCapOverdueDate(DateUtility.format8To10(loantemp.getOverdueDate()));//本金逾期起始日
            accLoan.setIntOverdueDate(DateUtility.format8To10(loantemp.getOverdueDate()));// int_overdue_date 利息逾期起始日赋值？？（逾期起始日？）overdue_date
        }
        accLoan.setLoanBalance(// nomalbalance修改为loan_balance
                loantemp.getPrincipalBal() == null ? BigDecimal.ZERO : loantemp.getPrincipalBal());

        accLoan.setReceIntCumu(
                loantemp.getInterestBal() == null ? BigDecimal.ZERO : loantemp.getInterestBal());// 贷款利息余额（int_accr应收利息（已记未结
        // 修改为：应收利息累计rece_int_cumu）
        accLoan.setUnpdPrinBal(// 逾期贷款本金余额（逾期贷款余额43 overdue_balance）修改为unpd_prin_bal 拖欠本金
                loantemp.getOverduePrin() == null ? BigDecimal.ZERO : loantemp.getOverduePrin());
        accLoan.setDelayIntCumu(// 逾期利息 由原来的逾期应收overdue_rece_int修改为欠息累计 delay_int_cumu
                loantemp.getOverdueInt() == null ? BigDecimal.ZERO : loantemp.getOverdueInt());
        accLoan.setUnpdIntArrPrn(// 罚息余额unpd_int_arr_prn1 修改为 应收罚息unpd_int_arr_prn
                loantemp.getPenaltyBal() == null ? BigDecimal.ZERO : loantemp.getPenaltyBal());
        // 注：逾期应收=表efp_loan.acc_loan中逾期本金（unpd_prin_bal）+逾期利息（delay_int_cumu）+罚息（unpd_int_arr_prn）
        BigDecimal overdueReceInt = accLoan.getUnpdPrinBal().add(accLoan.getDelayIntCumu())
                .add(accLoan.getUnpdIntArrPrn());
        // overdue_rece_int 逾期应收
        accLoan.setOverdueReceInt(overdueReceInt);

        // 2020/01/07 modify by ludayong
        // principal_bal	贷款本金余额
        BigDecimal principalBal = loantemp.getPrincipalBal() == null ? BigDecimal.ZERO : loantemp.getPrincipalBal();
        // overdue_prin	逾期贷款本金余额
        BigDecimal overduePrin =  loantemp.getOverduePrin() == null ? BigDecimal.ZERO : loantemp.getOverduePrin();
        // normal_balance 正常贷款余额(元)
        accLoan.setNormalBalance(principalBal.subtract(overduePrin));
        // normal_balance 逾期贷款余额(元)
        accLoan.setOverdueBalance(overduePrin);

        String intTypeMy = "";
        switch (loantemp.getIntType()) {
            case "N":
                intTypeMy = "1";
                break;
            default:
                break;
        }
        accLoan.setIrAdjustMode(intTypeMy); // 取字典库数据
        accLoan.setEnterAccount(loantemp.getCardNo());
        //repayment_account	还款账号
        accLoan.setRepaymentAccount(loantemp.getCardNo());

        String guaranteeFlagMy = "";
        switch (loantemp.getGuaranteeFlag()) {
            case "C101":
                guaranteeFlagMy = "30";
                break;
            case "C102":
                guaranteeFlagMy = "10";
                break;
            case "C103":
                guaranteeFlagMy = "20";
                break;
            case "C000":
            case "C104":
                guaranteeFlagMy = "00";
                break;
            default:
                break;
        }
        accLoan.setAssureMeansMain(guaranteeFlagMy);// 取字典库数据
        // pmt_type repayment_mode 还款方式141 1-等额本息=102;2-等额本金=201
        /* 数据库： 101 只还利息，到期还本 102 等额本息 201 等额本金 202 协议还款 */
        String pmtTypeMy = "";
        switch (loantemp.getPmtType()) {
            case "1":
                pmtTypeMy = "102";
                break;
            case "2":
                pmtTypeMy = "201";
                break;
            default:
                break;
        }
        accLoan.setRepaymentMode(pmtTypeMy);// 取字典库数据
        // accLoan.setRulingIr(newBigDecimal(loantemp.getInterestRate()));//改为执行年利率reality_ir_y
        accLoan.setRealityIrY(
                loantemp.getInterestRate() == null ? BigDecimal.ZERO : loantemp.getInterestRate());
        accLoan.setPrinFixedRate(
                loantemp.getPenaltyRate() == null ? BigDecimal.ZERO : loantemp.getPenaltyRate());
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//
        String currDate = sdfTime.format(new Date());
        accLoan.setLastUpdateTime(currDate);
        // loan_balance 借据余额 principal_bal 不赋值
        //accLoan.setLoanBalance(loantemp.getPrincipalBal() == null ? BigDecimal.ZERO : loantemp.getPrincipalBal());
        ////////////// 2019-1-23 cyj modify///////////////////////
        /*
         * normal_balance 正常贷款余额(元) 不赋值
         *
         * over_times_total 累计逾期期数 计算赋值   max_times_total 最高逾期期数 计算赋值
         *  auto_result 机评结果 关注 是否有字典 ????????
         *
         */
        //cyclic_way 额度循环标志 赋值？10 循环 查找字典
        accLoan.setCyclicWay(LimitConstant.CRD_LMT_TYPE_10);
        // accLoan.setRepayFreq();//repay_freq 还款频率 关注还款频率单位字段
        /////机构信息
        final String createUser = "admin";
        //final String legalOrgName = "广州银行智慧银行";
        // input_br_id 登记机构 赋值？跟合同
        // main_br_id 主管机构 赋值？跟合同
        // legal_org_code 机构法人代码 参考合同ESBClientConstance.Company
        // legal_org_name 机构法人名称 参考合同
        //accLoan.setInputBrId(ESBClientConstance.InstId );
        //accLoan.setMainBrId(ESBClientConstance.InstId );
        //accLoan.setLegalOrgCode(ESBClientConstance.Company);
        //accLoan.setLegalOrgName(legalOrgName);


        ///// 根据产品编号查询产品信息queryByPrdCode
        PrdInfoVO inPrdInfoVo = new PrdInfoVO();
        inPrdInfoVo.setPrdCode(loantemp.getProductCd());// prd_code 产品编号 马上：01020001 条件
        PrdInfoVO prodVo= prdInfoService.queryByPrdCode(inPrdInfoVo);
        if(prodVo!=null) {
            // prd_id 产品主键
            accLoan.setPrdId(prodVo.getPrdId());
            // prd_name 产品名称
            accLoan.setPrdName(prodVo.getPrdName());
        }
        ////// 根据借据编号查询申请表的相关信息
        NlsApplyInfoVO inNlsApplyInfoVO = new NlsApplyInfoVO();
        inNlsApplyInfoVO.setApplySeq(loantemp.getRefNbr());
        NlsApplyInfoVO queryNlsApplyInfoVO = nlsApplyInfoService.queryByPk(inNlsApplyInfoVO);// 查询网贷申请基本信息
        if (queryNlsApplyInfoVO != null) {
            // cus_id 客户编号 赋值
            accLoan.setCusId(queryNlsApplyInfoVO.getCusId());
            // loan_use_type 贷款用途 赋值？申请表取
            accLoan.setLoanUseType(queryNlsApplyInfoVO.getLoanPurpose());
            // 贷款合同编号 赋值
            accLoan.setContNo(queryNlsApplyInfoVO.getApplySeq());
            // applySeq 用信申请流水号
            accLoan.setApplySeq(queryNlsApplyInfoVO.getApplySeq());
            // 客户名称 赋值
            accLoan.setCusName(queryNlsApplyInfoVO.getCusName());
            // 证件类型 赋值
            accLoan.setCertType(queryNlsApplyInfoVO.getCertType());
            // 证件号码 赋值
            accLoan.setCertCode(queryNlsApplyInfoVO.getCertCode());
        }
        accLoan.setCreateUser(createUser);// create_user 创建人 admin
        accLoan.setCreateTime(currDate);// create_time 创建时间 赋值
        accLoan.setLastUpdateUser(createUser);// last_update_user 最后更新人 admin
        accLoan.setFirstDisbDate(DateUtility.format8To10(loantemp.getTxnDate()));// first_disb_date 首次放款日期
        // 赋值？（借据的开始时间：txn_date loan_start_date
        // 放款日期（贷款起始日15））
        // int_overdue_date 利息逾期起始日赋值？？（逾期起始日？）overdue_date 在上面
        accLoan.setFixedRate(
                loantemp.getInterestRate() == null ? BigDecimal.ZERO : loantemp.getInterestRate());// fixed_rate
        // 固定利率
        // 赋值？执行年利率
        ////////////// 2019-1-23 cyj modify///////////////////////
        try {
            //txn_date	放款日期
            String txnDate = Objects.isNull(loantemp.getTxnDate()) ? "" : loantemp.getTxnDate();
            //init_term	放款总期数
            int initTerm = Objects.isNull(loantemp.getInitTerm()) ? 0 : loantemp.getInitTerm();
            if(!StringUtil.isNullorBank(txnDate)) {
                //原到期日期
                String OrigExpiDate = DateUtility.ADD_MONTH(DateUtility.format8To10(txnDate), initTerm);
                //accLoan.setOrigExpiDate(OrigExpiDate);// 原到期日期
                //accLoan.setLoanEndDate(OrigExpiDate);// 贷款终止日
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("原到期日期、贷款终止日计算出错，错误信息："+e.getMessage());
        }
        //modify by 2020/03/04 dengqiwen 同步账务日期  modify by 2020/04/08 dengqiwen 日期减1天
        accLoan.setBizDate(DateUtility.ADD_DAY(DateUtility.format8To10(loantemp.getBizDate()),-1));
        return accLoan;

    }

    /**
     *需求编号：【2019D1204】（马上账务文件同步分页处理）
     *问题编号：【2019D1204】（马上账务文件同步分页处理）
     *开发人员：【ludayong】
     *创建日期：【2019/11/27 11:31】
     *功能描述：分页同步借据信息
     *修改日期：【2019/11/27 11:31】
     *修改描述：
     */
    public boolean syncLoanInfo(List<GzBankLoanFileTempVO> list) {
        boolean result = false;
        int num = 0;
        try {
            if (list != null && list.size() > 0) {
                logger.info("有 "+list.size() +" 条马上同步过来的临时数据记录数");
                //批量更新
                List<AccLoanVO> accloanUpdateLists = new ArrayList<AccLoanVO>();
                List<AccLoanVO> accloanInsertLists = new ArrayList<AccLoanVO>();
                List<NlsApplyInfoVO> nlsApplyInfoUpdateLists = new ArrayList<NlsApplyInfoVO>();
                List<CtrLoanContVO> ctrLoanContUpdateLists = new ArrayList<CtrLoanContVO>();
                for (int i = 0; i < list.size(); i++) {
                    logger.info("开始循环第"+i+"条数据");
                    try {
                        String intTypeMy = "";String guaranteeFlagMy = "";String pmtTypeMy = "";
                        // 得到ref_nbr
                        GzBankLoanFileTempVO loantemp = list.get(i);

                        if (loantemp != null) {
                            logger.info("得到第"+i+"条数据，loantemp = list.get(i)如果不为空，得到loantemp.getRefNbr()："+loantemp.getRefNbr());
                            // 根据申请流水号去查放款审批流水表 0待放款 1已放款
                            logger.info("根据申请流水号去查放款审批流水表");
                            String billNo = loantemp.getRefNbr();// 临时表的借据编号ref_nbr对应本代表bill_no
                            // 根據得到的billNo查詢實體
                            AccLoanVO acc_loan = new AccLoanVO();
                            acc_loan.setBillNo(billNo);
                            AccLoanVO accLoan = accLoanService.queryByPk(acc_loan);
                            String status = "1";
                            if (accLoan == null ||StringUtils.isEmpty(accLoan.getAccountStatus()) || "0".equals(accLoan.getAccountStatus())) {
                                String applySeq = loantemp.getRefNbr();// `apply_seq` varchar(64) NOT NULL COMMENT '申请流水号',
                                // 根据合同号去查看放款申请表的状态 是否为已放款
                                NlsApplyInfoVO voByapplySeq = new NlsApplyInfoVO();
                                voByapplySeq.setApplySeq(applySeq);
                                NlsApplyInfoVO voByContModel = nlsApplyInfoService.queryByPk(voByapplySeq);
                                if (voByContModel != null) {
                                    status = voByContModel.getDnSts();
                                    logger.info("根据申请流水号去查放款审批流水表，有数据，得到放款状态：" + voByContModel.getDnSts());
                                }else{
                                    status ="0";
                                }
                            }


                            if (DN_STS_1.equals(status)) {// （放款=联合放款成功状态：放款流水表里）
                                logger.info("DN_STS_1=："+DN_STS_1+"得到放款为联合放款成功状态");
                                if (accLoan != null) {// 本地表能找到对应的借据信息，则修改
                                    logger.info("本地表的借据信息表有在申请表为联合放款成功的数据，开始修改");
                                    // 2019-1-23 modify by cyj
                                    /*
                                     * 贷款本金余额（原来对应 正常贷款余额(元)normal_balance不赋值） 修改为loan_balance借据余额
                                     * 贷款利息余额（int_accr应收利息（已记未结 修改为：应收利息累计rece_int_cumu） 逾期贷款本金余额（逾期贷款余额43
                                     * overdue_balance）修改为unpd_prin_bal 拖欠本金 逾期利息 由原来的逾期应收overdue_rece_int修改为欠息累计
                                     * delay_int_cumu 罚息余额unpd_int_arr_prn1 修改为 应收罚息unpd_int_arr_prn
                                     */
                                    accLoan.setContNo(loantemp.getRefNbr());
                                    accLoan.setPrdCode(loantemp.getProductCd());// 根据产品编号查相关数据
                                    accLoan.setCurType(loantemp.getCurrency());// 取字典库数据CNY 人民币//156?
                                    String statusMy = "";
                                    switch (loantemp.getTxnStatus()) {
                                        case "1":// 1：正常
                                            statusMy = "1";
                                            break;
                                        case "2":// 2：延期
                                        case "3":// 3：提前结清
                                        case "5":// 5：结清
                                            statusMy = "4";// 结清
                                            // // settl_date 结清日期 赋值  结清时： 业务日期
                                            accLoan.setSettlDate(DateUtility.format8To10(loantemp.getBizDate()));
                                            logger.info("马上数据过来状态为："+loantemp.getTxnStatus()+"更新借据表2：延期/3：提前结清/5：结清的日期为："+loantemp.getBizDate());
                                            //accLoan.setLoanEndDate(DateUtility.format8To10(loantemp.getBizDate()));// 贷款终止日
                                            //logger.info(" 贷款终止日："+DateUtility.format8To10(loantemp.getBizDate()));
                                            break;
                                        case "9":// 9理赔结清
                                            statusMy = "11";// 理赔结清
                                            // // settl_date 结清日期 赋值  结清时： 业务日期
                                            accLoan.setSettlDate(DateUtility.format8To10(loantemp.getBizDate()));
                                            logger.info("更新借据表9理赔结清日期为："+loantemp.getBizDate());
                                            //accLoan.setLoanEndDate(DateUtility.format8To10(loantemp.getBizDate()));// 贷款终止日
                                            //logger.info(" 贷款终止日："+DateUtility.format8To10(loantemp.getBizDate()));
                                            break;
                                        case "4":// 4：逾期
                                        case "7":// 7：逾期90天强制终止
                                            statusMy = "10";// 逾期
                                            break;
                                        case "6":
                                            statusMy = "9";// 核销
                                            //accLoan.setLoanEndDate(DateUtility.format8To10(loantemp.getBizDate()));// 贷款终止日
                                            //logger.info(" 贷款终止日："+DateUtility.format8To10(loantemp.getBizDate()));
                                            break;
                                        default:
                                            break;
                                    }
                                    //  modify by ludayong 2020/01/16 【马上】新增贷款状态转换为网贷台账状态
                                    // 贷款状态转换为网贷台账状态
                                    statusMy = SDicMappingUtil.getLocalSysDicVal("TxnStatus", loantemp.getTxnStatus());
                                    logger.info("贷款状态：" + loantemp.getTxnStatus() + "，转换为网贷台账状态：" + statusMy);

                                    accLoan.setAccountStatus(statusMy);// 取字典库数据
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//
                                    accLoan.setLoanStartDate(DateUtility.format8To10(loantemp.getTxnDate()));
                                    // curr_term 加上 当前期数（在本地表缺少需加上）
                                    accLoan.setCurrTerm(new BigDecimal(loantemp.getCurrTerm() == null ? 0 : loantemp.getCurrTerm()));
                                    // 报表需要字段 ：overdue_days 逾期天数 loan_term贷款期限（init_term） load_term_type期限类型 （默认:月）
                                    // curr_term当前期数
                                    accLoan.setOverdueDays(
                                            new BigDecimal(loantemp.getOverdueDays() == null ? 0 : loantemp.getOverdueDays()));
                                    accLoan.setLoanTerm(new BigDecimal(loantemp.getInitTerm() == null ? 0 : loantemp.getInitTerm()));
                                    accLoan.setLoadTermType(BdLoanConstant.TERM_TYPE_M);
                                    accLoan.setIntRateType(loantemp.getIntRateType());// 利率类型
                                    accLoan.setLoanAmount(loantemp.getTxnAmt() == null ? BigDecimal.ZERO : loantemp.getTxnAmt());
                                    //如果没有逾期，则为空
                                    if(loantemp.getOverdueDate() !=null) {
                                        accLoan.setCapOverdueDate(DateUtility.format8To10(loantemp.getOverdueDate()));//本金逾期起始日
                                        accLoan.setIntOverdueDate(DateUtility.format8To10(loantemp.getOverdueDate()));// int_overdue_date 利息逾期起始日赋值？？（逾期起始日？）overdue_date
                                    }
                                    accLoan.setLoanBalance(// nomalbalance修改为loan_balance
                                            loantemp.getPrincipalBal() == null ? BigDecimal.ZERO : loantemp.getPrincipalBal());

                                    accLoan.setReceIntCumu(
                                            loantemp.getInterestBal() == null ? BigDecimal.ZERO : loantemp.getInterestBal());// 贷款利息余额（int_accr应收利息（已记未结
                                    /////////overdue_balance	overdue_prin	,1																					// 修改为：应收利息累计rece_int_cumu）
                                    accLoan.setUnpdPrinBal(// 逾期贷款本金余额（逾期贷款余额43 overdue_balance）修改为unpd_prin_bal 拖欠本金
                                            loantemp.getOverduePrin() == null ? BigDecimal.ZERO : loantemp.getOverduePrin());
                                    accLoan.setDelayIntCumu(// 逾期利息 由原来的逾期应收overdue_rece_int修改为欠息累计 delay_int_cumu
                                            loantemp.getOverdueInt() == null ? BigDecimal.ZERO : loantemp.getOverdueInt());
                                    accLoan.setUnpdIntArrPrn(// 罚息余额unpd_int_arr_prn1 修改为 应收罚息unpd_int_arr_prn
                                            loantemp.getPenaltyBal() == null ? BigDecimal.ZERO : loantemp.getPenaltyBal());
                                    // 注：逾期应收=表efp_loan.acc_loan中逾期本金（unpd_prin_bal）+逾期利息（delay_int_cumu）+罚息（unpd_int_arr_prn）
                                    BigDecimal overdueReceInt = accLoan.getUnpdPrinBal().add(accLoan.getDelayIntCumu())
                                            .add(accLoan.getUnpdIntArrPrn());
                                    // overdue_rece_int 逾期应收
                                    accLoan.setOverdueReceInt(overdueReceInt);

                                    // 2020/01/07 modify by ludayong
                                    // principal_bal	贷款本金余额
                                    BigDecimal principalBal = loantemp.getPrincipalBal() == null ? BigDecimal.ZERO : loantemp.getPrincipalBal();
                                    // overdue_prin	逾期贷款本金余额
                                    BigDecimal overduePrin =  loantemp.getOverduePrin() == null ? BigDecimal.ZERO : loantemp.getOverduePrin();
                                    // normal_balance 正常贷款余额(元)
                                    accLoan.setNormalBalance(principalBal.subtract(overduePrin));
                                    // normal_balance 逾期贷款余额(元)
                                    accLoan.setOverdueBalance(overduePrin);

                                    switch (loantemp.getIntType()) {
                                        case "N":
                                            intTypeMy = "1";
                                            break;
                                        default:
                                            break;
                                    }
                                    accLoan.setIrAdjustMode(intTypeMy); // 取字典库数据
                                    accLoan.setEnterAccount(loantemp.getCardNo());
                                    //repayment_account	还款账号
                                    accLoan.setRepaymentAccount(loantemp.getCardNo());

                                    switch (loantemp.getGuaranteeFlag()) {
                                        case "C101":
                                            guaranteeFlagMy = "30";
                                            break;
                                        case "C102":
                                            guaranteeFlagMy = "10";
                                            break;
                                        case "C103":
                                            guaranteeFlagMy = "20";
                                            break;
                                        case "C000":
                                        case "C104":
                                            guaranteeFlagMy = "00";
                                            break;
                                        default:
                                            break;
                                    }
                                    accLoan.setAssureMeansMain(guaranteeFlagMy);// 取字典库数据
                                    // pmt_type repayment_mode 还款方式141 1-等额本息=102;2-等额本金=201
                                    /* 数据库： 101 只还利息，到期还本 102 等额本息 201 等额本金 202 协议还款 */

                                    switch (loantemp.getPmtType()) {
                                        case "1":
                                            pmtTypeMy = "102";
                                            break;
                                        case "2":
                                            pmtTypeMy = "201";
                                            break;
                                        default:
                                            break;
                                    }
                                    accLoan.setRepaymentMode(pmtTypeMy);// 取字典库数据
                                    // accLoan.setRulingIr(newBigDecimal(loantemp.getInterestRate()));//改为执行年利率reality_ir_y
                                    accLoan.setRealityIrY(
                                            loantemp.getInterestRate() == null ? BigDecimal.ZERO : loantemp.getInterestRate());
                                    accLoan.setPrinFixedRate(
                                            loantemp.getPenaltyRate() == null ? BigDecimal.ZERO : loantemp.getPenaltyRate());
                                    SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//
                                    String currDate = sdfTime.format(new Date());
                                    accLoan.setLastUpdateTime(currDate);
                                    // loan_balance 借据余额 principal_bal
                                    /////////normal_balance	principal_bal	,1  不赋值
                                    //accLoan.setLoanBalance(loantemp.getPrincipalBal() == null ? BigDecimal.ZERO : loantemp.getPrincipalBal());

                                    ////////////// 2019-1-23 cyj modify///////////////////////
									/*
									 * normal_balance 正常贷款余额(元) 不赋值
									 *
									 * over_times_total 累计逾期期数 计算赋值
									 * -- 查询累计逾期期数
										select count(1) FROM
										(
										-- 查询已还，但是逾期还款
										select term from loan_repay_plan plan
										 join loan_repay_detail  detail
										on detail.LOAN_NO = plan.ref_nbr
										and plan.term=detail.repay_term
										and plan.stmt_date<detail.SETL_APPLY_DT
										where plan.ref_nbr='AndroidAyh02100240449R79muA89'
										UNION
										-- 查询未还，已经超期
										select term from loan_repay_plan where ref_nbr='AndroidAyh02100240449R79muA89' and status='O'
										and stmt_date<curdate()
										) as a

									 *   max_times_total 最高逾期期数 计算赋值
									 *  auto_result 机评结果 关注 是否有字典 ????????
									 *
									 */
                                    //cyclic_way 额度循环标志 赋值？10 循环 查找字典
                                    accLoan.setCyclicWay(LimitConstant.CRD_LMT_TYPE_10);
                                    // accLoan.setRepayFreq();//repay_freq 还款频率 关注还款频率单位字段
                                    /////机构信息
                                    final String createUser = "admin";
                                    //final String legalOrgName = "广州银行智慧银行";
                                    // input_br_id 登记机构 赋值？跟合同
                                    // main_br_id 主管机构 赋值？跟合同
                                    // legal_org_code 机构法人代码 参考合同ESBClientConstance.Company
                                    // legal_org_name 机构法人名称 参考合同
                                    //accLoan.setInputBrId(ESBClientConstance.InstId );
                                    //accLoan.setMainBrId(ESBClientConstance.InstId );
                                    //accLoan.setLegalOrgCode(ESBClientConstance.Company);
                                    //accLoan.setLegalOrgName(legalOrgName);


                                    ///// 根据产品编号查询产品信息queryByPrdCode

                                    PrdInfoVO inPrdInfoVo = new PrdInfoVO();
                                    inPrdInfoVo.setPrdCode(loantemp.getProductCd());// prd_code 产品编号 马上：01020001 条件
                                    PrdInfoVO prodVo= prdInfoService.queryByPrdCode(inPrdInfoVo);
                                    if(prodVo!=null) {
                                        // prd_id 产品主键
                                        accLoan.setPrdId(prodVo.getPrdId());
                                        // prd_name 产品名称
                                        accLoan.setPrdName(prodVo.getPrdName());
                                    }
                                    ////// 根据借据编号查询申请表的相关信息
                                    NlsApplyInfoVO inNlsApplyInfoVO = new NlsApplyInfoVO();
                                    inNlsApplyInfoVO.setApplySeq(loantemp.getRefNbr());
                                    NlsApplyInfoVO queryNlsApplyInfoVO = nlsApplyInfoService.queryByPk(inNlsApplyInfoVO);// 查询网贷申请基本信息
                                    if (queryNlsApplyInfoVO != null) {
                                        // cus_id 客户编号 赋值
                                        accLoan.setCusId(queryNlsApplyInfoVO.getCusId());
                                        // loan_use_type 贷款用途 赋值？申请表取
                                        accLoan.setLoanUseType(queryNlsApplyInfoVO.getLoanPurpose());
                                        // 贷款合同编号 赋值
                                        accLoan.setContNo(queryNlsApplyInfoVO.getApplySeq());
                                        // applySeq 用信申请流水号
                                        accLoan.setApplySeq(queryNlsApplyInfoVO.getApplySeq());
                                        // 客户名称 赋值
                                        accLoan.setCusName(queryNlsApplyInfoVO.getCusName());
                                        // 证件类型 赋值
                                        accLoan.setCertType(queryNlsApplyInfoVO.getCertType());
                                        // 证件号码 赋值
                                        accLoan.setCertCode(queryNlsApplyInfoVO.getCertCode());
                                    }
                                    accLoan.setCreateUser(createUser);// create_user 创建人 admin
                                    //accLoan.setCreateTime(currDate);// create_time 创建时间 赋值
                                    accLoan.setLastUpdateUser(createUser);// last_update_user 最后更新人 admin
                                    accLoan.setFirstDisbDate(DateUtility.format8To10(loantemp.getTxnDate()));// first_disb_date 首次放款日期
                                    // 赋值？（借据的开始时间：txn_date loan_start_date
                                    // 放款日期（贷款起始日15））
                                    //accLoan.setIntOverdueDate(DateUtility.format8To10(loantemp.getOverdueDate()));// 前面已经赋值  int_overdue_date 利息逾期起始日
                                    // 赋值？？（逾期起始日？）overdue_date
                                    accLoan.setFixedRate(
                                            loantemp.getInterestRate() == null ? BigDecimal.ZERO : loantemp.getInterestRate());// fixed_rate
                                    // 固定利率
                                    // 赋值？执行年利率
                                    try {
                                        //txn_date	放款日期
                                        String txnDate = Objects.isNull(loantemp.getTxnDate()) ? "" : loantemp.getTxnDate();
                                        //init_term	放款总期数
                                        int initTerm = Objects.isNull(loantemp.getInitTerm()) ? 0 : loantemp.getInitTerm();
                                        if(!StringUtil.isNullorBank(txnDate)) {
                                            //原到期日期
                                            String OrigExpiDate = DateUtility.ADD_MONTH(DateUtility.format8To10(txnDate), initTerm);
                                            //accLoan.setOrigExpiDate(OrigExpiDate);// 原到期日期
                                            //accLoan.setLoanEndDate(OrigExpiDate);// 贷款终止日
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error("原到期日期、贷款终止日计算出错，错误信息："+e.getMessage());
                                    }
                                    ////////////// 2019-1-23 cyj modify///////////////////////
                                    logger.info("本地表的借据信息表有在申请表为联合放款成功的数据，结束修改");
                                    //modify by 2020/03/04 dengqiwen 同步账务日期  modify by 2020/04/08 dengqiwen 日期减1天
                                    accLoan.setBizDate(DateUtility.ADD_DAY(DateUtility.format8To10(loantemp.getBizDate()),-1));
                                    accloanUpdateLists.add(accLoan);
                                    logger.info("修改返回值num"+num);

                                    logger.info("本地表的借据信息表有在申请表为联合放款成功的数据，修改成功");
                                    logger.info("修改成功后更新合同号相关值，开始");
                                    CtrLoanContVO ctrLoanContVO=new CtrLoanContVO();
                                    ctrLoanContVO.setContNo(loantemp.getRefNbr());
                                    ctrLoanContVO=ctrLoanContService.queryByPk(ctrLoanContVO);
                                    //int_rate_type	利率类型	赋值 - 固定利率
                                    if(ctrLoanContVO != null)
                                    {
                                        ctrLoanContVO.setIntRateType(loantemp.getIntRateType());  //利率类型
                                        //fixed_rate	固定利率	赋值
                                        //ctrLoanContVO.setFixedRate(intTypeMy);
                                        ///ir_adjust_mode	利率调整方式	查看赋值
                                        //ctrLoanContVO.setIrAdjustMode(irAdjustMode);
                                        //reality_ir_y	执行利率(年)	赋值
                                        ctrLoanContVO.setRealityIrY(loantemp.getInterestRate() == null ? BigDecimal.ZERO : loantemp.getInterestRate());
                                        //repayment_mode	还款方式	赋值
                                        ctrLoanContVO.setRepaymentMode(pmtTypeMy);
                                        //repayment_period	还款周期	1
                                        ctrLoanContVO.setRepaymentPeriod(1);///////
                                        //repayment_period_type	还款周期单位	月
                                        ctrLoanContVO.setRepaymentPeriodType(BdLoanConstant.TERM_TYPE_M);//////
                                        //assure_means_main	担保方式	赋值
                                        ctrLoanContVO.setAssureMeansMain(guaranteeFlagMy);
                                        ctrLoanContUpdateLists.add(ctrLoanContVO);

                                    }

                                } else {
                                    logger.info("放款状态 为已放款但没有借据信息 则新增借据信息,调用新增借据方法开始");
                                    // 放款状态 为已放款 但没有借据信息 则新增借据信息
                                    AccLoanVO accLoanVo = insetAccLoan(loantemp);
                                    accloanInsertLists.add(accLoanVo);
                                    logger.info("放款状态 为已放款但没有借据信息 则新增借据信息，新增台账表成功!");
                                    logger.info("新增台账表成功后更新合同相关信息，开始!");
                                    //更新借据信息后 更新合同相关信息
                                    CtrLoanContVO ctrLoanContVO=new CtrLoanContVO();
                                    ctrLoanContVO.setContNo(loantemp.getRefNbr());
                                    ctrLoanContVO=ctrLoanContService.queryByPk(ctrLoanContVO);
                                    if(ctrLoanContVO != null)
                                    {
                                        //int_rate_type	利率类型	赋值
                                        ctrLoanContVO.setIntRateType(loantemp.getIntRateType());  //利率类型
                                        //fixed_rate	固定利率	赋值
                                        //ctrLoanContVO.setFixedRate(intTypeMy);
                                        ///ir_adjust_mode	利率调整方式	查看赋值
                                        //ctrLoanContVO.setIrAdjustMode(irAdjustMode);
                                        //reality_ir_y	执行利率(年)	赋值
                                        ctrLoanContVO.setRealityIrY(loantemp.getInterestRate() == null ? BigDecimal.ZERO : loantemp.getInterestRate());
                                        //repayment_mode	还款方式	赋值
                                        ctrLoanContVO.setRepaymentMode(pmtTypeMy);
                                        //repayment_period	还款周期	1
                                        ctrLoanContVO.setRepaymentPeriod(1);///////
                                        //repayment_period_type	还款周期单位	月
                                        ctrLoanContVO.setRepaymentPeriodType(BdLoanConstant.TERM_TYPE_M);//////
                                        //assure_means_main	担保方式	赋值
                                        ctrLoanContVO.setAssureMeansMain(guaranteeFlagMy);
                                        logger.info("新增台账表成功后更新合同相关信息，结束!");
                                        ctrLoanContUpdateLists.add(ctrLoanContVO);
                                        logger.info("新增台账表成功后更新合同相关信息，返回值num："+num);
                                    }

                                }
                            } else if (DN_STS_3.equals(status)) {
                                logger.info("放款状态为 待放款时 则新增借据信息 并且修改状态为 放款成功");
                                // 放款状态为 待放款时 则新增借据信息 并且修改状态为 放款成功 (我们没有接收到马上的放款成功的消息，所以没有在借据表生成记录)
                                AccLoanVO accLoanVo = insetAccLoan(loantemp);
                                accloanInsertLists.add(accLoanVo);
                                logger.info("新增借据信息成功，开始修改申请表的状态为 放款成功");
                                // 修改状态为 放款成功
                                NlsApplyInfoVO voBySts = new NlsApplyInfoVO();
                                voBySts.setApplySeq(loantemp.getRefNbr());
                                voBySts.setDnSts("1");
                                logger.info("新增借据信息成功，开始修改申请表的状态为 放款成功，开始");

                                nlsApplyInfoUpdateLists.add(voBySts);
                                logger.info("新增借据信息成功，更新合同相关信息，开始");
                                //更新借据信息后 更新合同相关信息
                                CtrLoanContVO ctrLoanContVO=new CtrLoanContVO();
                                ctrLoanContVO.setContNo(loantemp.getRefNbr());
                                ctrLoanContVO=ctrLoanContService.queryByPk(ctrLoanContVO);
                                if(ctrLoanContVO != null)
                                {
                                    //int_rate_type	利率类型	赋值
                                    ctrLoanContVO.setIntRateType(loantemp.getIntRateType());  //利率类型
                                    //fixed_rate	固定利率	赋值
                                    //ctrLoanContVO.setFixedRate(intTypeMy);
                                    ///ir_adjust_mode	利率调整方式	查看赋值
                                    //ctrLoanContVO.setIrAdjustMode(irAdjustMode);
                                    //reality_ir_y	执行利率(年)	赋值
                                    ctrLoanContVO.setRealityIrY(loantemp.getInterestRate() == null ? BigDecimal.ZERO : loantemp.getInterestRate());
                                    //repayment_mode	还款方式	赋值
                                    ctrLoanContVO.setRepaymentMode(pmtTypeMy);
                                    //repayment_period	还款周期	1
                                    ctrLoanContVO.setRepaymentPeriod(1);///////
                                    //repayment_period_type	还款周期单位	月
                                    ctrLoanContVO.setRepaymentPeriodType(BdLoanConstant.TERM_TYPE_M);//////
                                    //assure_means_main	担保方式	赋值
                                    ctrLoanContVO.setAssureMeansMain(guaranteeFlagMy);
                                    logger.info("新增借据信息成功，更新合同相关信息，结束");
                                    ctrLoanContUpdateLists.add(ctrLoanContVO);
                                }


                            }else {
                                logger.info("非待放款、放款成功的用信申请信息");
                                String tableName = "NlsApplyInfo用信表";
                                String erroMsg = "";
                                String tempTotal = "";
                                String acountTotal = "";
                                String type = "0";
                                String updateDelInster = "更新";
                                String no = loantemp.getRefNbr();
                                String eMsg = "非待放款、放款成功的用信申请信息";
                                accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);

                            }
                        }
                    } catch (Exception e) {
                        logger.info("循环第"+i+"条数据出现异常");
                        logger.error("循环第"+i+"条数据出现异常");
                        logger.error("更新台账表出错!", e);
                        e.printStackTrace();
                        String tableName = "AccLoan借据表";
                        String erroMsg = "";
                        String tempTotal = "";
                        String acountTotal = "";
                        String type = "0";
                        String updateDelInster = "更新";
                        String no = "";
                        String eMsg = e.getMessage();
                        accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);
                    }
                    logger.info("结束循环第"+i+"条数据");
                }
                if(accloanUpdateLists.size()>0){
                    num = accLoanService.batchUpdate(accloanUpdateLists);
                    if (num == -1) {
                        StringBuilder billNos = new StringBuilder();
                        for (AccLoanVO accLoanVO: accloanUpdateLists) {
                            billNos.append(accLoanVO.getBillNo());
                        }
                        logger.info("本地表的借据信息表有在申请表为联合放款成功的数据，批量修改出错");
                        logger.error("批量更新acc_loan贷款台账表数据发生异常,借据编号："+billNos.toString());
                        String tableName = "AccLoan借据表";
                        String erroMsg = "";
                        String tempTotal = "";
                        String acountTotal = "";
                        String type = "0";
                        String updateDelInster = "批量更新";
                        String no = accloanUpdateLists.get(0).getBillNo();
                        String eMsg = "批量更新台账表出错!";
                        accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type,
                                updateDelInster, no, eMsg);
                    }
                }
                if(accloanInsertLists.size()>0){
                    num=accLoanService.batchInsert(accloanInsertLists);
                    if (num == -1) {
                        StringBuilder billNos = new StringBuilder();
                        for (AccLoanVO accLoanVO: accloanInsertLists) {
                            billNos.append(accLoanVO.getBillNo());
                        }
                        logger.info("本地表的借据信息表有在申请表为联合放款成功的数据，批量修改出错，批量新增acc_loan贷款台账表出错");
                        logger.error("批量新增acc_loan贷款台账表出错!借据编号："+billNos.toString());
                        String tableName = "acc_loan贷款台账表";
                        String erroMsg = "";
                        String tempTotal = "";
                        String acountTotal = "";
                        String type = "0";
                        String updateDelInster = "批量新增";
                        String no = accloanInsertLists.get(0).getBillNo();
                        String eMsg = "批量新增台账表出错!";
                        accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type,
                                updateDelInster, no, eMsg);
                    }
                }
                if (num != -1) {//更新借据信息后 更新合同相关信息
                    if(nlsApplyInfoUpdateLists.size()>0){
                        num=nlsApplyInfoService.batchUpdate(nlsApplyInfoUpdateLists);
                        logger.info("非待放款、放款成功的用信申请信息时 ,新增借据信息,返回值num："+num);
                        if (num == -1) {
                            StringBuilder applySeqs = new StringBuilder();
                            for (NlsApplyInfoVO nlsApplyInfoVO: nlsApplyInfoUpdateLists) {
                                applySeqs.append(nlsApplyInfoVO.getApplySeq());
                            }
                            logger.info("新增借据信息成功，开始批量修改申请表的状态为 放款成功，失败！返回结果rs："+num);
                            logger.error("新增借据信息成功，开始批量修改申请表的状态为 放款成功，失败！流水号："+applySeqs.toString());
                            String tableName = "nls_apply_info网贷申请基本表";
                            String erroMsg = "";
                            String tempTotal = "";
                            String acountTotal = "";
                            String type = "0";
                            String updateDelInster = "批量更新";
                            String no = nlsApplyInfoUpdateLists.get(0).getApplySeq();
                            String eMsg = "更新还款状态出错!";
                            accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type,
                                    updateDelInster, no, eMsg);

                        }
                    }
                    if(ctrLoanContUpdateLists.size()>0){
                        num=ctrLoanContService.batchUpdate(ctrLoanContUpdateLists);
                        logger.info("新增台账表成功后更新贷款合同表相关信息 ,返回值num："+num);
                        if (num == -1) {
                            StringBuilder contNos = new StringBuilder();
                            for (CtrLoanContVO ctrLoanContVO: ctrLoanContUpdateLists) {
                                contNos.append(ctrLoanContVO.getContNo());
                            }
                            logger.info("新增借据信息成功，批量更新贷款合同表ctr_loan_cont相关信息，失败！返回结果："+num);
                            logger.error("批量更新贷款合同表ctr_loan_cont相关信息出错!,合同编号:"+contNos.toString());
                            String tableName = "ctr_loan_cont贷款合同表";
                            String erroMsg = "";
                            String tempTotal = "";
                            String acountTotal = "";
                            String type = "0";
                            String updateDelInster = "批量更新";
                            String no = ctrLoanContUpdateLists.get(0).getContNo();
                            String eMsg = "批量更新贷款合同表相关信息出错!";
                            accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type,
                                    updateDelInster, no, eMsg);

                        }
                    }
                }

            }
            result = true;
        } catch (Exception e) {
            logger.info("try 更新台账发生异常");
            logger.error("更新台账表出错!", e);
            e.printStackTrace();
            String tableName = "AccLoan借据表";
            String erroMsg = "";
            String tempTotal = "";
            String acountTotal = "";
            String type = "0";
            String updateDelInster = "更新";
            String no = "";
            String eMsg = e.getMessage();
            accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);
        }
        return result;
    }
}
